package cn.xfdzx.android.apps.shop.activity;

import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.adapter.MyAddressListAdapter;
import cn.xfdzx.android.apps.shop.adapter.NearLoactionAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.AddAddressBeen;
import cn.xfdzx.android.apps.shop.bean.AddressListBeen;
import cn.xfdzx.android.apps.shop.bean.DeleteAddressBeen;
import cn.xfdzx.android.apps.shop.bean.LocationInfo;
import cn.xfdzx.android.apps.shop.contract.AddressListContract;
import cn.xfdzx.android.apps.shop.contract.ItemClickListener;
import cn.xfdzx.android.apps.shop.evenbus.HomeAdressMessage;
import cn.xfdzx.android.apps.shop.presenter.AddressListPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;

import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;
import static cn.xfdzx.android.apps.shop.apps.Constants.START_CODE;

/**
 * @author gzk
 * @data 2020/03/25
 * 定位详情页
 */
public class LocationActivity extends BaseMvpActivity <AddressListPresenter> implements AddressListContract.View,PoiSearch.OnPoiSearchListener {

    @BindView(R.id.ll_location_search)
    LinearLayout locationSearch;//搜索
    @BindView(R.id.tv_location_address)
    TextView locationTv;//定位当前位置
    @BindView(R.id.ll_location_again)
    LinearLayout locationAgain;//重新定位
    @BindView(R.id.location_rv_nearyby)
    RecyclerView locationRvNearyBy;//附近位置
    @BindView(R.id.ll_state)
    LinearLayout llState;
    @BindView(R.id.rv_my_address)
    RecyclerView rv_my_address;//我的收货地址列表
    @BindView(R.id.ll_open)
    LinearLayout ll_open;//展开
    @BindView(R.id.ll_close)
    LinearLayout ll_close;//关闭
    @BindView(R.id.tv_send_to_address)
    TextView tv_send_to_address;//送至--

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;


    private List<LocationInfo> list = new ArrayList<>();
    private NearLoactionAdapter nearLoactionAdapter;

    private RelativeLayout.LayoutParams item_bar;
    private MyAddressListAdapter myAddressListAdapter;//我的地址列表适配器
    private List<AddressListBeen.DataBean> mAddressList;//我的地址列表集合
    private List<AddressListBeen.DataBean> mAddressListFour = new ArrayList<>();//我的地址列表只显示4条集合
    private boolean isOpen;//判断是否选择全部展开
    private String pageForm="";//判断是否是首页跳转

    @Override
    public int getLayoutId() {
        return R.layout.activity_location;
    }

    @Override
    public void initView() {
        pageForm = getIntent().getStringExtra("pageForm")==null?"":getIntent().getStringExtra("pageForm");
        initHigh();
        getLocation();
        mPresenter = new AddressListPresenter();
        mPresenter.attachView(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        locationRvNearyBy.setLayoutManager(linearLayoutManager);
        nearLoactionAdapter = new NearLoactionAdapter(list, this);
        locationRvNearyBy.setNestedScrollingEnabled(false);
        locationRvNearyBy.setAdapter(nearLoactionAdapter);
        initRecycle();
        //请求我的地址列表
        mPresenter.initAddressData(false, false,  "1","200");
        nearLoactionAdapter.setOnItemClickListener(new  ItemClickListener() {
            @Override
            public void onItemClick(int position) {
                EventBus.getDefault().post(new HomeAdressMessage(list.get(position).getTitle(),
                        list.get(position).getLatitude()+"",list.get(position).getLonTitude()+""));
                Intent intent = new Intent(LocationActivity.this, MainActivity.class);
                intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
            }
        });

        if (EmptyUtil.isNotEmpty(getIntent().getStringExtra("send_to_address"))){
            tv_send_to_address.setVisibility(View.VISIBLE);
            tv_send_to_address.setText("送至:"+getIntent().getStringExtra("send_to_address"));
        }else {
            tv_send_to_address.setVisibility(View.GONE);
        }

    }

    /**
     * 初始化我的地址列表recycle
     * **/
    private void initRecycle() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        rv_my_address.setLayoutManager(linearLayoutManager);
        myAddressListAdapter = new MyAddressListAdapter(mAddressList);
        rv_my_address.setAdapter(myAddressListAdapter);
    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (!isGpsEnabled(getApplicationContext())) {
                Utils.toastMessage(getApplicationContext(), "未开启GPS");
            } else {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        //可在其中解析amapLocation获取相应内容。

                        locationTv.setText(aMapLocation.getAoiName());//显示当前位置
                        //附近搜索
                        nearLocation(aMapLocation);
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
//                    locationTv.setText("定位失败");
                    }
                }
            }
        }
    };

    private void nearLocation(AMapLocation aMapLocation) {

        double latitude = aMapLocation.getLatitude();//获取纬度
        double longitude = aMapLocation.getLongitude();//获取经度

        //不设置POI的类别，默认返回“餐饮服务”、“商务住宅”、“生活服务”这三种类别的POI
        PoiSearch.Query query = new PoiSearch.Query(aMapLocation.getAoiName(), "", aMapLocation.getCity());
        query.setPageSize(4);
        query.setPageNum(1);
        PoiSearch search = new PoiSearch(this, query);
        search.setBound(new PoiSearch.SearchBound(new LatLonPoint(latitude,
                longitude), 200));//设置周边搜索的中心点以及半径
        search.setOnPoiSearchListener(this);
        search.searchPOIAsyn();
    }


    public void getLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        //允许模拟定位
        mLocationOption.setMockEnable(true);
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        if (null != mLocationClient) {
            mLocationClient.setLocationOption(mLocationOption);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取最近3s内精度最高的一次定位结果：
        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
//        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
//        mLocationClient.onDestroy();
    }


    @OnClick({R.id.iv_location_back, R.id.tv_location_add_address, R.id.ll_location_search, R.id.ll_location_again,
            R.id.ll_location_more_address,R.id.ll_open,R.id.ll_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_location_back:
                //返回
                finish();
                break;
            case R.id.tv_location_add_address:
                //跳转到新增收货地址
                Intent intent = new Intent(this, AddAddressActivity.class);
                intent.putExtra("from","first");
                startActivityForResult(intent,START_CODE);
                break;
            case R.id.ll_location_more_address:
                //跳转到更多地址页面
                Intent intent_moer_address = new Intent(this, MoreAddressMapActivity.class);
                intent_moer_address.putExtra("pageForm",pageForm);
                startActivity(intent_moer_address);
                break;
            case R.id.ll_location_search:
                //点击搜索框跳转
                Intent intent_search = new Intent(this, SearchAddressActivity.class);
                intent_search.putExtra("pageForm",pageForm);
                startActivity(intent_search);
                break;
            case R.id.ll_location_again:
                //重新启动定位
                mLocationClient.startLocation();
                break;
            case R.id.ll_open://展开我的地址
                Log.e("mList",list.size()+"--ll_open-");
                isOpen = true;
                ll_open.setVisibility(View.GONE);
                ll_close.setVisibility(View.VISIBLE);
                if (true){
                    Log.e("mList",list.size()+"--ll_opentrue-");
                    myAddressListAdapter.refreshDatas(mAddressList);
                }else {
                    Log.e("mList",list.size()+"--ll_openfalse-");
                    myAddressListAdapter.refreshDatas(mAddressListFour);
                }

                break;
            case R.id.ll_close://关闭我的地址
                Log.e("mList",list.size()+"--ll_close-");
                isOpen = false;
                ll_open.setVisibility(View.VISIBLE);
                ll_close.setVisibility(View.GONE);
                if (true){
                    Log.e("mList",list.size()+"--ll_closetrue-");
                    myAddressListAdapter.refreshDatas(mAddressListFour);
                }else {
                    Log.e("mList",list.size()+"--ll_closefalse-");
                    myAddressListAdapter.refreshDatas(mAddressList);
                }
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mLocationClient != null) {
            //停止定位后，本地定位服务并不会被销毁
            mLocationClient.stopLocation();
        }
    }

    /**
     * 附近位置，
     *
     * @param poiResult
     * @param i
     */
    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        list.clear();
        ArrayList<PoiItem> pois = poiResult.getPois();
        for (PoiItem poi : pois) {

            LocationInfo info = new LocationInfo();
            LatLonPoint point = poi.getLatLonPoint();

            info.setTitle(poi.getTitle());
            info.setAddress(poi.getSnippet());
            info.setLatitude(point.getLatitude());
            info.setLonTitude(point.getLongitude());
            list.add(info);

            Log.i("名称", poi.getTitle());
            Log.i("详细地址", info.getAddress());

        }
        nearLoactionAdapter.setList(list);
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onError(Throwable throwable) {

    }

    /**
     * 请求地址列表成功
     * **/
    @Override
    public void onInitSuccess(AddressListBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            mAddressList = bean.getData();
            if (mAddressList.size()>4){
                mAddressListFour.clear();
                mAddressListFour.add(mAddressList.get(0));
                mAddressListFour.add(mAddressList.get(1));
                mAddressListFour.add(mAddressList.get(2));
                mAddressListFour.add(mAddressList.get(3));
                myAddressListAdapter.refreshDatas(mAddressListFour);
            }else {
                myAddressListAdapter.refreshDatas(mAddressList);
            }


        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDelectSuccess(DeleteAddressBeen bean, int position) {

    }

    @Override
    public void onAddAddressSuccess(AddAddressBeen bean, int position, int index) {

    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void finishLoadMore() {

    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    @Override
    protected void onDestroy() {
        list.clear();
        list=null;
        if (mLocationClient != null) {
            //销毁定位客户端，同时销毁本地定位服务。
            mLocationClient.onDestroy();
        }
        mPresenter.detachView();
        super.onDestroy();
    }

    //判断GPS是否开启
    private boolean isGpsEnabled(Context context) {
        LocationManager locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        // 判断GPS模块是否开启
        return locationManager != null && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == START_CODE) {
                //请求我的地址列表
                mPresenter.initAddressData(false, false,  "1","200");
            }
        }
    }

}
